package com.example.order.feign.config;

import feign.Logger;
import feign.RetryableException;
import feign.codec.ErrorDecoder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;

import java.util.Date;

/**
 * @Author: 唐佳辉
 * @CreateTime： 2025-05-08-08:47
 * @Description: 配置日志输出级别
 * @Version：1.0
 */
public class BaseFeignConfig {


    @Bean
    @ConditionalOnMissingBean // 这里如果不加@ConditionalOnMissingBean那么独立配置是无法生效的，原理在后面补充
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    public ErrorDecoder errorDecoder() {
        return (methodKey, response) -> {
            HttpStatus status = HttpStatus.valueOf(response.status());
            if (status.is5xxServerError()) {
                // 将5xx错误转换为可重试异常
                return new RetryableException(
                        response.status(),
                        "Server Error with status " + response.status(),
                        response.request().httpMethod(),
                        new Date(),
                        response.request());
            }
            // 其他错误按默认处理
            return new ErrorDecoder.Default().decode(methodKey, response);
        };
    }

}
